﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Xml;
using Pampa.Grid.Exceptions;

namespace Pampa.Grid.Core
{
    public class MainFilterGroupDefinition
    {
        string id;
        string label;
        string join;
        IList<MainFilterDefinition> items;

        public MainFilterGroupDefinition()
        {
            items = new List<MainFilterDefinition>();
        }

        public string Id
        {
            get { return id; }
            set { id = value; }
        }

        public string Label
        {
            get { return label; }
            set { label = value; }
        }

        public string Join
        {
            get { return join; }
            set { join = value; }
        }
        
        public IList<MainFilterDefinition> Items
        {
            get { return items; }
        }

        public void AddItem(MainFilterDefinition item)
        {
            item.Parent = this;
            items.Add(item);
        }

        public static MainFilterGroupDefinition LoadFromXml(XmlNode node)
        {
            Assembly assembly = Assembly.GetAssembly(typeof(MainFilterGroupDefinition));

            if (node.Name == "MainFilterGroup")
            {
                MainFilterGroupDefinition groupDefinition = new MainFilterGroupDefinition();
                groupDefinition.LoadXml(node);
                return groupDefinition;
            }
            else
            {
                throw (new GridConfigurationException("Item " + node.Name + " is not expected inside MainFilterDefinition."));
            }
        }

        public virtual void LoadXml(XmlNode node)
        {
            try
            {
                this.Id = node.Attributes["Id"].Value;
                this.Label = node.Attributes["Label"].Value;

                if (node.Attributes["Join"] != null)
                    this.Join = node.Attributes["Join"].Value;

                foreach (XmlNode itemNode in node.ChildNodes)
                {
                    MainFilterDefinition item = MainFilterDefinition.LoadFromXml(itemNode);
                    AddItem(item);
                }
            }
            catch (Exception ex)
            {
                throw new GridConfigurationException("El formato del archivo de configuración es incorrecto.", ex);
            }
        }
    }
}
